package com.dsg.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class loginController {


    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @PostMapping("/login")
    public String login(String username,String password){
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return "redirect:/index";
    }

    @ExceptionHandler(Exception.class)
    public String exception(Exception ex, Model model){
        String error = "";
        if(ex instanceof UnknownAccountException){
            error = "用户名和密码不符！";
        }else if(ex instanceof IncorrectCredentialsException){
            error = "用户名和密码不符！";
        }
        model.addAttribute("error",error);
        return "login";

    }
}
